package com.ocean.courtyard.command;

import com.ocean.courtyard.core.datasource.SqlSessionImpl;
import com.ocean.courtyard.entity.CourtyardHome;
import com.ocean.courtyard.message.Message;
import com.ocean.courtyard.util.FileUtils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;

public class TpSetCommand implements CommandExecutor {

    private final JavaPlugin plugin;

    private final MultiverseCore core;

    private final SqlSessionImpl sqlSession;

    private final Message message;

    private final Player player;


    public TpSetCommand(JavaPlugin plugin, SqlSessionImpl sqlSession, Message message, Player player) {
        this.plugin = plugin;
        this.core = JavaPlugin.getPlugin(MultiverseCore.class);
        this.sqlSession = sqlSession;
        this.message = message;
        this.player = player;
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
        Player player = (Player) sender;
        CourtyardHome home = sqlSession.getHome(player);
        String homeServer = home.getServer();
        String playerServer = FileUtils.getServerName(plugin.getConfig());
        String currentWorldName = player.getWorld().getName();

        if (!homeServer.equals(playerServer) || !currentWorldName.equals(home.getWorldName())) {
            message.sendNoHomeWorldMessage(player);
            return false;
        }

        MVWorldManager manager = core.getMVWorldManager();
        String worldName = FileUtils.getWorldPath(player, plugin);
        if (!manager.isMVWorld(worldName)) {
            message.sendHomeNotFoundMessage(player);
            return false;
        }

        Location location = player.getLocation();
        MultiverseWorld mvWorld = manager.getMVWorld(home.getWorldName());
        mvWorld.setSpawnLocation(location);
        sqlSession.tpSet(player.getName(), location.getX(), location.getY(), location.getZ());
        message.sendTpSetSuccess(player);
        return true;
    }
}
